﻿using Clirelmgt.Manager;
using Clirelmgt.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Clirelmgt.Controllers
{
    public partial class AdminController : Controller
    {
        //
        // GET: /Admin/

        public ActionResult List(string ID)
        {
            //if (Session["crmsession"] == null)
            //{
            //    return RedirectToAction("Login", "Account");
            //}
            string langid="en-US";
            MetaListPage listPage = new MetaListPage();
            ListModel model = new ListModel();
            using (CRMDataContext dataContext = new CRMDataContext())
            {
                var appObjects = dataContext.GetAppObject(ID.ToUpper(), "LIST", true);
                foreach (var appObject in appObjects)
                {
                    string formXml = appObject.AppMetaData;
                    listPage = Utility.DeserializeString<MetaListPage>(formXml) as MetaListPage;
                    string tableXml = appObject.TableMetadata;
                    string tableName = appObject.LinkTable;
                    MetaTable tableMetadata = Utility.DeserializeString<MetaTable>(tableXml) as MetaTable;
                    foreach (MetaFormField field in listPage.Fields)
                    {
                        List<MetaTableField> tableFields = tableMetadata.Fields.Where(obj => (obj.Name.ToUpper() == field.Name.ToUpper())).ToList();
                        if (tableFields.Count > 0)
                        {
                            field.DataType = tableFields[0].DataType;
                            field.FieldLength = tableFields[0].FieldLength;
                            field.Options = tableFields[0].Options;
                            List<MetaLanguage> languageLables = tableFields[0].Labels.Where(obj => (obj.LangID == langid)).ToList();
                            if (languageLables.Count > 0)
                            {
                                field.DisplayLabel = languageLables[0].LabelText;
                            }
                        }
                    }

                    model.DisplayFields = new Dictionary<string, string>();
                    foreach (MetaFormField field in listPage.Fields)
                    {
                        model.DisplayFields.Add(field.Name, field.DisplayLabel);
                    }

                    model.TableFields = tableMetadata.Fields.ToList();

                    string selectQuery = DataHelper.GetSqlSelectStatement(tableName, listPage);
                    DataSet resultSet = DataAccess.RunSelectStatement(selectQuery);
                    if (resultSet != null)
                    {
                        if (resultSet.Tables.Count > 0)
                        {
                            model.RecordTable = resultSet.Tables[0];
                        }
                    }

                    model.Title = listPage.Name;
                    model.CardName = listPage.CardPage;
                }
            }

            return View(model);
        }

        public Dictionary<string, object> ContextData { get; set; }

        public ActionResult Card(string ID, string mode, string key)
        {
            if (Session["crmsession"] == null)
            {
                return RedirectToAction("Login", "Account");
            }

            string langid = Utility.GetLanguage(Session["crmsession"]);
            bool isnew = true;
            ContextData = new Dictionary<string, object>();
            if (Request.QueryString.AllKeys.Count() > 0)
            {
                if (mode.ToLowerInvariant() == "edit")
                {
                    isnew = false;
                    ViewBag.No = key;
                    ViewBag.SubmitBtn = "Update";
                }
                else
                {
                    isnew = true;
                    ViewBag.No = "NEW";
                    ViewBag.SubmitBtn = "Save";
                }
            }

            MetaCardPage cardPage = new MetaCardPage();
            using (CRMDataContext dataContext = new CRMDataContext())
            {
                var appObjects = dataContext.GetAppObject(ID, "CARD", true);
                foreach (var appObject in appObjects)
                {
                    string formXml = appObject.AppMetaData;
                    cardPage = Utility.DeserializeString<MetaCardPage>(formXml) as MetaCardPage;
                    string tableName = appObject.LinkTable;
                    MetaTable tableMetadata = Utility.DeserializeString<MetaTable>(appObject.TableMetadata) as MetaTable;
                    
                    foreach (MetaFieldGroup fieldGroup in cardPage.FieldGroups)
                    {
                        foreach (MetaFormField field in fieldGroup.Fields)
                        {
                            MetaTableField tableField = tableMetadata.Fields.Where(obj => (obj.Name == field.Name)).ToList()[0];
                            List<MetaLanguage> languageLables = tableField.Labels.Where(obj => (obj.LangID == langid)).ToList();
                            if (languageLables.Count > 0)
                            {
                                field.DisplayLabel = languageLables[0].LabelText;
                            }
                            field.DataType = tableField.DataType;
                            field.FieldLength = tableField.FieldLength;
                            field.Required = false;

                            if (field.DataType == FieldDataType.Key)
                            {
                                cardPage.PrefixKey = tableMetadata.PrefixKey;
                            }
                            else if (field.DataType == FieldDataType.Select)
                            {
                                field.Options = tableField.Options;
                            }
                            else if (field.DataType == FieldDataType.Table)
                            {
                                field.Options = tableField.Options;
                            }

                            ContextData.Add(field.Name, field.FieldValue);
                        }
                    }

                    if (!isnew)
                    {
                        string selectQuery = DataHelper.GetSqlSelectStatement(tableName, ContextData, string.Format("[No]='{0}'", key));
                        DataSet resultSet = DataAccess.RunSelectStatement(selectQuery);
                        if (resultSet.Tables.Count > 0)
                        {
                            if (resultSet.Tables[0].Rows.Count > 0)
                            {
                                DataRow record = resultSet.Tables[0].Rows[0];
                                foreach (MetaFieldGroup fieldGroup in cardPage.FieldGroups)
                                {
                                    foreach (MetaFormField field in fieldGroup.Fields)
                                    {
                                        field.FieldValue = record[field.Name].ToString();
                                    }
                                }
                            }
                        }
                    }

                    if (TempData.ContainsKey("CardPage"))
                    {
                        TempData["CardPage"] = cardPage;
                    }
                    else
                    {
                        TempData.Add("CardPage", cardPage);
                    }
                }
            }

            return View(cardPage);
        }

        [HttpPost]
        public ActionResult Card(string ID, string mode, string key, FormCollection formData)
        {
            if (Session["crmsession"] == null)
            {
                return RedirectToAction("Login", "Account");
            }

            string userId = Utility.GetUserId(Session["crmsession"]);
            string langid = Utility.GetLanguage(Session["crmsession"]);
            bool isnew = true;
            ContextData = new Dictionary<string, object>();
            if (Request.QueryString.AllKeys.Count() > 0)
            {
                if (mode.ToLowerInvariant() == "edit")
                {
                    isnew = false;
                    ViewBag.No = key;
                    ViewBag.SubmitBtn = "Update";
                }
                else
                {
                    isnew = true;
                    ViewBag.No = "NEW";
                    ViewBag.SubmitBtn = "Save";
                }
            }

            MetaCardPage cardPage = new MetaCardPage();
            cardPage = TempData["CardPage"] as MetaCardPage;
            using (CRMDataContext dataContext = new CRMDataContext())
            {
                foreach (MetaFieldGroup fieldGroup in cardPage.FieldGroups)
                {
                    foreach (MetaFormField field in fieldGroup.Fields)
                    {
                        if (Request.Form.AllKeys.Contains(field.Name))
                        {
                            if (field.DataType == FieldDataType.Bool)
                            {
                                string value = "false";
                                if (Request.Form[field.Name] == "on")
                                {
                                    value = "true";
                                }

                                field.FieldValue = value;
                            }
                            else
                            {
                                field.FieldValue = Request.Form[field.Name];
                            }

                            ContextData.Add(field.Name, field.FieldValue);
                        }
                    }
                }

                if (isnew)
                {
                    string insertQuery = DataHelper.GetSqlInsertStatement(cardPage.LinkTable, cardPage.PrefixKey, ContextData, userId);
                    DataAccess.ExecuteNonQuery(insertQuery);
                }
                else
                {
                    string updateQuery = DataHelper.GetSqlUpdateStatement(cardPage.LinkTable, ContextData, string.Format("[No]='{0}'", key), userId);
                    DataAccess.ExecuteNonQuery(updateQuery);
                }

                if (TempData.ContainsKey("CardPage"))
                {
                    TempData["CardPage"] = cardPage;
                }
                else
                {
                    TempData.Add("CardPage", cardPage);
                }
            }

            return View(cardPage);
        }
    }
}
